<template>
  <div style="padding: 20px; height: 550px; overflow: scroll">
    <a-menu @click="onSearchMember" v-model:selectedKeys="currentKey" mode="horizontal" :items="items" />
    <!--我的关注页面-->
    <a-input-search
        v-if="currentKey[0] === 'my-focus' || currentKey[0] === 'add-focus'"
        style="width: 600px; padding: 15px"
        v-model:value="searchValue"
        placeholder="昵称、电话、邮箱"
        @search="onSearchMember({key: currentKey[0]})"
    >
    </a-input-search>
    <div style="text-align: left; padding: 10px">
      <a-list v-if="currentKey[0] === 'my-focus' || currentKey[0] === 'add-focus'"
              item-layout="horizontal" size="small" :data-source="listData">
        <template #footer>
        </template>
        <template #renderItem="{ item }">
          <a-list-item key="item.title">
            <template #actions>
              <a-tag v-if="item.ack === 0 || item.focusStatus===0" color="orange">等待回关</a-tag>
              <a-tag v-if="item.ack === 1 || item.focusStatus===1" color="green">已互关</a-tag>
              <a v-if="item.ack === 1 || item.focusStatus===1">
                <component :is="MessageOutlined" style="margin-right: 15px" @click="startChat(item.toMemberId)"/>
              </a>
              <a v-if="typeof item.focusStatus !== 'undefined' && item.focusStatus === 2 || item.focusStatus === -1">
                <component :is="PlusCircleOutlined" style="margin-right: 15px" @click="focusUser(item.id)"/>
              </a>
            </template>
            <a-list-item-meta :description="item.sign">
              <template #title>
                <a :href="item.href">{{ item.nickname }}</a>
              </template>
              <template #avatar><a-avatar :src="item.header" /></template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>

      <div v-if="currentKey[0] === 'focus-apply'">
        <a-collapse
            v-model:activeKey="activeKey"
            :bordered="false"
            style="background: rgb(255, 255, 255)"
        >
          <template #expandIcon="{ isActive }">
            <caret-right-outlined :rotate="isActive ? 90 : 0" />
          </template>
          <a-collapse-panel key="1" header="发起的申请" :style="customStyle">
            <p>
              <a-list
                  item-layout="horizontal" size="small" :data-source="applyList.ownApplyList">
                <template #footer>
                </template>
                <template #renderItem="{ item }">
                  <a-list-item key="item.title">
                    <template #actions>
                      {{item.applyTime}}
                      <a-tag v-if="item.ack === -1" color="red">对方已拒绝</a-tag>
                      <a-tag v-if="item.ack === 1" color="green">对方已接受</a-tag>
                      <a-tag v-if="item.ack === 0" color="processing">等待对方验证</a-tag>
                    </template>
                    <a-list-item-meta :description="item.greetingMsg">
                      <template #title>
                        <a :href="item.href">{{ item.nickname }}</a>
                      </template>
                      <template #avatar><a-avatar :src="item.header" /></template>
                    </a-list-item-meta>
                  </a-list-item>
                </template>
              </a-list>
            </p>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="收到的申请" :style="customStyle">
            <p>
              <a-list
                  item-layout="horizontal" size="small" :data-source="applyList.otherApplyList">
                <template #footer>
                </template>
                <template #renderItem="{ item }">
                  <a-list-item key="item.title">
                    <template #actions>
                      <div v-if="item.ack===0">
                        <component :is="checkOutlined" style="margin-right: 15px" @click="handleApply(item.id, 1)"/>
                        <component :is="closeOutlined" style="margin-right: 15px" @click="handleApply(item.id, -1)"/>
                      </div>
                      <div v-else>
                        <a-tag v-if="item.ack === -1" color="red">已拒绝</a-tag>
                        <a-tag v-if="item.ack === 1" color="green">已接受</a-tag>
                      </div>
                    </template>
                    <a-list-item-meta :description="item.greetingMsg">
                      <template #title>
                        <a :href="item.href">{{ item.nickname }}</a>
                      </template>
                      <template #avatar><a-avatar :src="item.header" /></template>
                    </a-list-item-meta>
                  </a-list-item>
                </template>
              </a-list>
            </p>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </div>
    <!-- 添加关注页面-->
    <div style="text-align: left; padding: 10px" v-if="currentKey[0] === 'add-focus'"/>

    <a-modal v-model:open="applyOpen" title="好友申请" @ok="handleOk">
      <p>
        <a-textarea
            v-model:value="applyGreeting"
            placeholder="打个招呼吧"
            :auto-size="{ minRows: 2, maxRows: 5 }"
        />
      </p>
    </a-modal>
  </div>
</template>

<script setup>
import {h, ref, onBeforeMount, watch, reactive} from 'vue';
import {CaretRightOutlined, MailOutlined, AppstoreOutlined,MessageOutlined, PlusCircleOutlined, CheckOutlined, CloseOutlined} from '@ant-design/icons-vue';
import request from "@/utils/request";
import {message} from "ant-design-vue";
import {useSocketStore} from "@/utils/websocket";
import router from "@/router";
import {publish} from "pubsub-js";
import checkOutlined from "@ant-design/icons-vue/lib/icons/CheckOutlined";
import closeOutlined from "@ant-design/icons-vue/lib/icons/CloseOutlined";

const currentKey = ref(['my-focus']);
const items = ref([
  {
    key: 'my-focus',
    icon: () => h(MailOutlined),
    label: '我的关注',
  },
  {
    key: 'add-focus',
    icon: () => h(AppstoreOutlined),
    label: '添加关注',
  },
  {
    key: 'focus-apply',
    label: '好友申请'
  }
]);

//折叠面板
const activeKey = ref(['2']);
const customStyle =
    'background: #f7f7f7;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden';

watch(() => useSocketStore().msg, message => {
  // 好友申请消息处理
  if (message.type === 5) {
    request({
      url: '/im/member/get-targetInfo',
      method: 'post',
      data: {fromId: message.toId, toId: message.fromId}
    }).then(res => {
      if (res.code === 0) {
        let temp = {id: message.fromId, header: res.data.userInfo.header, nickname: res.data.userInfo.nickname,
          greetingMsg: message.msgContent, applyTime: message.sendTime, ack: 0}
        applyList.otherApplyList.push(temp)
      } else {
        console.log(res.msg)
      }
    })
  }
})

//好友申请视图
const applyOpen = ref(false);
let applyTargetId = ref(null)
let applyGreeting = ref('')
let applyList = reactive({otherApplyList: [], ownApplyList: []})
// key: applyList.otherApplyList[i].id, value: i
let applyListIndexMap = new Map()

let session = JSON.parse(localStorage.getItem("session"))

let searchValue = ref('')

const onSearchMember=(item)=>{
  if(item.key === 'my-focus' || item.key === 'add-focus') {
    postSearch(item.key)
  }
  if (item.key === 'focus-apply') {
    //获取好友申请列表
    request({
      url: `/im/member/list-focus/${session.id}`,
      method: 'get',
    }).then(res => {
      console.log(res)
      if(res.code === 0) {
        applyList.otherApplyList = []
        applyList.ownApplyList = []
        for (let i = 0; i < res.data.otherApplyList.length; i++) {
          applyList.otherApplyList.push(res.data.otherApplyList[i])
          applyListIndexMap.set(res.data.otherApplyList[i].id, i)
        }
        applyList.ownApplyList = res.data.ownApplyList
      } else {
        message.warn(res.msg)
      }
    })
  }
}

let listData = ref([]);
const postSearch = (type)=>{
  let postData = {key: searchValue.value, type: typeof type==="undefined" ? currentKey.value[0] : type, userId: session.id}
  request({
    url: '/im/member/query-member-focus',
    method: 'post',
    data: postData
  }).then(res=>{
    console.log(res)
    if(res.code === 0) {
      listData.value = res.data
    } else {
      message.error(res.msg)
    }
  }).catch(err=>{
    console.log(`请求用户列表异常${err.message}`)
  })
}

const startChat = (userId)=>{
  publish('routerChange', 2)
  router.push({
    name: 'chatContent',
    params: {userId: router.currentRoute.value.params.userId},
    query: {toId: userId}
  })
}

const focusUser = (userId)=> {
  applyOpen.value = true
  applyTargetId.value = userId
}

const handleOk = e => {
  applyOpen.value = false;
  // 发起好友申请
  useSocketStore().sendMsgParam.type = 5
  useSocketStore().sendMsgParam.toId = applyTargetId.value
  useSocketStore().sendMsgParam.msgContent = applyGreeting.value
  useSocketStore().sendMsgParam.status = 0
  useSocketStore().sendMsg()
  useSocketStore().sendMsgParam.msgContent = ''

  request({
    url: '/im/member/add-focus',
    method: 'post',
    data: {fromId: Number.parseInt(session.id), toId: Number.parseInt(applyTargetId.value)}
  }).then(res => {
    if(res.code === 0) {
      message.success(res.msg)
    }else {
      message.warn(res.msg)
    }
  })
};

const handleApply = (userId, ackType) => {
  request({
    url: '/im/member/handle-focusApply',
    method: 'post',
    data: {fromId: Number.parseInt(session.id), toId: userId, ack: ackType}
  }).then(res => {
    if(res.code === 0){
      message.success(res.msg)
      let index = applyListIndexMap.get(userId)
      if (typeof index !== "undefined") {
        applyList.otherApplyList[index].ack = ackType
      }
    } else {
      message.warn(res.msg)
    }
  })
}

onBeforeMount(_=>{
  onSearchMember({key: 'my-focus'})
})
</script>